﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LabyCLI
{
    public partial class frmGoto : Form
    {
        Terminal frm = Terminal.Instance;

        static int lineCount;

        public frmGoto()
        {
            //Initialize lineCount
            lineCount = frm.GetCurrentTerminal().Lines.Count();

            InitializeComponent();

            lbl_LineNumbers.Text = "Line number (1 - " + lineCount + "):";
        }

        private void txtbox_Line_TextChanged(object sender, EventArgs e)
        {
            int input;
            if (int.TryParse(txtbox_Line.Text, out input))
            {
                if (input <= lineCount)
                {
                    btn_OK.Enabled = true;
                }
                else
                {
                    btn_OK.Enabled = false;
                    //Number too high.
                }
            }
            else
            {
                btn_OK.Enabled = false;
                //Is not an integer.
            }
        }

        private void txtbox_Line_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (btn_OK.Enabled)
                {
                    ScrollToLine(int.Parse(txtbox_Line.Text));

                    DialogResult = DialogResult.OK;
                }
                else
                {
                    MessageBox.Show("The line number: " + lineCount + " could not be selected.", Application.ProductName);
                }
            }
            else if (e.KeyCode == Keys.Escape)
            {
                DialogResult = DialogResult.Cancel;
            }
        }

        void ScrollToLine(int lineNumber)
        {
            if (lineNumber > frm.GetCurrentTerminal().Lines.Count()) return;
            
            if (!string.IsNullOrEmpty(frm.GetCurrentTerminal().Lines[lineNumber]))
            {
                frm.GetCurrentTerminal().SelectionStart = frm.GetCurrentTerminal().Find(frm.GetCurrentTerminal().Lines[lineNumber]);
                frm.GetCurrentTerminal().ScrollToCaret();
            }
        }

        private void btn_OK_Click(object sender, EventArgs e)
        {
            ScrollToLine(int.Parse(txtbox_Line.Text));
        }
    }
}
